import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { staticRoutes, layoutRoute } from './routes';
import http from '@/utils/request';
import { usePermissionStore } from '@/stores/permission';

const router = createRouter({
  history: createWebHistory(),
  routes: [...staticRoutes, layoutRoute],
  scrollBehavior: () => ({ top: 0 })
});

const whiteList = ['/login', '/404', '/front'];

router.beforeEach(async (to, from, next) => {
  console.log('[导航开始] 当前路径:', to.path, '来源路径:', from.path);

  if (to.meta.title) {
    document.title = `${to.meta.title} - 小花在线图书馆`;
  } else {
    document.title = '小花在线图书馆';
  }

  const userStore = useUserStore();


  const permissionStore = usePermissionStore();
  console.log('[用户状态] token存在:', !!userStore.token, '角色:', userStore.roles);

  // 1. 白名单检查
  if (whiteList.some(path => to.path.startsWith(path))) {
    console.log('[白名单] 直接放行');
    next();
    return;
  }

  // 2. 权限路由标识
  const isAuthRoute = to.path.startsWith('/dashboard/');

  // 3. 未登录访问受保护路由
  if (!userStore.token && isAuthRoute) {
    console.warn('[权限拦截] 未登录访问受保护路由');
    next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
    return;
  }

  // 4. 已登录处理逻辑
  if (userStore.token) {
    console.log('[已登录] 开始处理逻辑');
    
    // 4.1 获取用户信息（添加角色验证日志）
    if (!userStore.library_users.roles?.length) {
      console.log('[用户信息] 开始获取角色信息');
      try {
        const infoRes = await http.get('/user/getInfo');
        userStore.roles = infoRes.data.roles;
        console.log('[用户角色] 当前角色:', userStore.roles); // 新增角色日志
      } catch (error) {
        userStore.logout();
        next('/login');
        return;
      }
    }

    // 4.2 动态路由处理（修复触发条件）
    const shouldGenerate = userStore.roles?.length > 0 && 
                          !localStorage.getItem('routeGenerated') && // 改用本地存储直接读取
                          !router.hasRoute('DashboardRoot'); // 使用官方API检查路由存在性

    console.log('[深度调试]', {
      roles: userStore.roles,
      localStorageStatus: localStorage.getItem('routeGenerated'),
      dashboardRouteExists: router.hasRoute('DashboardRoot')
    });

    // 强制重置生成状态（调试用）
    if (process.env.NODE_ENV === 'development') {
      localStorage.removeItem('routeGenerated');
      permissionStore.hasGenerated = false;
    }
                          !permissionStore.hasGenerated &&
                          // 改进点1：添加路由名称过滤，排除静态路由
                          !router.getRoutes().some(r => r.name === 'DashboardRoot');

    console.log('[调试信息]', {
      hasRoles: userStore.roles?.length > 0,
      notGenerated: !permissionStore.hasGenerated,
      noDashboard: !router.getRoutes().some(r => r.name === 'DashboardRoot'),
      staticRoutes: router.getRoutes().filter(r => r.path.startsWith('/dashboard'))
    }, "shouldGenerate:", shouldGenerate);

    if (shouldGenerate) {
      console.log('[路由生成] 开始生成动态路由');
      
      await permissionStore.generateRoutes(userStore.roles);

      // 统一路由添加逻辑
      permissionStore.routes.forEach(route => {
        const normalizedPath = route.path.startsWith('/dashboard/') 
          ? route.path 
          : `/dashboard/${route.path.replace(/^\/?/, '')}`;

        router.addRoute('DashboardRoot', {
          ...route,
          path: normalizedPath,
          children: route.children?.map(child => ({
            ...child,
            path: `${normalizedPath}/${child.path}`
          }))
        });
      });

      // 改进路由查找方式
      const dashboardRoute = router.getRoutes().find(r => 
        r.path === '/dashboard' && 
        r.name === 'DashboardRoot'
      );

      if (dashboardRoute) {
        permissionStore.routes = dashboardRoute.children || [];
        console.log('[路由状态] dashboard子路由:', dashboardRoute.children);
      } else {
        console.error('[路由错误] 未找到dashboard根路由');
      }

      await nextTick();
      permissionStore.setHasGenerated(true);
      router.replace(to.redirectedFrom || '/dashboard/overview');
      return;
    }

    // 4.3 已登录访问登录页
    if (to.path === '/login') {
      console.log('[导航拦截] 已登录访问登录页，重定向到控制台');
      next('/dashboard/overview');
      return;
    }
  }

  console.log('[导航放行] 进入最终next()');
  next();
});

export { router };
export default router;


console.log('[路由状态] 当前注册路由:', 
  router.getRoutes().map(r => ({ path: r.path, name: r.name }))
);